import numpy as np
import pandas as pd
import pyqtgraph as pg

from PyQt5 import QtWidgets
from PyQt5.Qt import *
from ui_Window import Ui_MainWindow

class Stats(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.w = QMainWindow()  # 实例化QMainWindow类
        self.ui.setupUi(self.w)  # 主窗体对象调用setupUi方法，对QMainWindow对象进行设置

        # Use PySide2 to load .ui file
        # have to load and connect PlotWidget sperately
        # ui_file_name = "main.ui"
        # ui_file = QFile(ui_file_name)
        # ui_file.open(QFile.ReadOnly)
        # loader = QUiLoader()
        # self.ui = loader.load(ui_file)
        # ui_file.close()

        # Use PyQt5 to load .ui
        # 报错，怀疑是版本不兼容
        # self.ui = uic.loadUi("main.ui")
        # parameters
        self.data = pd.read_table('19221342.txt')
        self.data = self.data.values
        self.data = np.append(self.data, np.arange(0, len(self.data), 1).reshape(2798, 1), axis=1)  # data
        self.color = ['r', 'g', 'b', 'y']   # 每个轴的数据显示颜色
        self.Vn = 0 # 车辆数
        self.Counting = []  # 车辆存在时间
        self.Vmess = [] # 车辆信息

        self.ui.Plot.setXRange(0, 333)
        self.ui.Plot.setYRange(1000, 3200)

        self.ui.Seton.clicked.connect(self.showRoll)
        self.ui.Count_v.clicked.connect(self.count_v)
        self.ui.X_data.clicked.connect(self.renew)
        self.ui.Y_data.clicked.connect(self.renew)
        self.ui.Z_data.clicked.connect(self.renew)
        self.ui.Z1_data.clicked.connect(self.renew)

    def showRoll(self):
        self.renew()
        # 设定定时器
        self.timer = pg.QtCore.QTimer()
        # 定时器信号绑定 update_data 函数
        self.timer.timeout.connect(self.update_data)
        # 定时器间隔50ms，可以理解为 50ms 刷新一次数据
        self.timer.start(50)

    def update_data(self):
        self.ui.Plot.clear()
        self.ui.Plot.setXRange(0,333)
        self.ui.Plot.setYRange(1000, 3200)
        for check in self.Checked:
            self.plot = self.ui.Plot.plot( pen=pg.mkPen(self.color[check]))
            self.data[:-1,check] = self.data[1:,check]
            self.plot.setData(self.data[:,check])
        if self.ui.Grid.isChecked():
            self.ui.Plot.showGrid(x=True,y=True)
        else:
            self.ui.Plot.showGrid(x=False, y=False)

    def renew(self):
        self.Checked = []
        if self.ui.X_data.isChecked():
            self.Checked.append(0)
        if self.ui.Y_data.isChecked():
            self.Checked.append(1)
        if self.ui.Z_data.isChecked():
            self.Checked.append(2)
        if self.ui.Z1_data.isChecked():
            self.Checked.append(3)

    def count_v(self):
        self.Vn = 0  # 车辆数
        self.Counting = []  # 车辆存在时间
        self.Vmess = []  # 车辆信息
        if len(self.data)>0:
            for i in range(1, len(self.data)):
                if self.data[i][1] >= 2100 or self.data[i][1] <= 1900:
                    self.Counting.append(self.data[i][4])
                elif len(self.Counting) > 0:
                    if self.data[i][4] == self.Counting[-1] + 1 and self.data[i][1]-self.data[i-1][1] > 0:
                        start = self.Counting[1] / 333
                        end = self.Counting[-1] / 333
                        # 车长4.5m
                        speed = 4.5 / (end - start)
                        self.Vn += 1
                        self.Counting = []
                        self.Vmess.append([self.Vn, start, speed])
            for row in range(0, len(self.Vmess)):
                self.ui.tableWidget.insertRow(0)
                for col in range(0, 3):
                    item = QTableWidgetItem(str(round(self.Vmess[row][col], 3)))
                    self.ui.tableWidget.setItem(0, col, item)
                    item.setFlags(Qt.ItemIsEnabled)
        else:
            self.ui.tableWidget.insertRow(0)
            self.ui.tableWidget.setItem(0, 0, QTableWidgetItem('Erro:'))
            self.ui.tableWidget.setItem(0, 1, QTableWidgetItem('Load data!'))

app = QtWidgets.QApplication([])
stats = Stats()
stats.w.show()
app.exec_()
